package interviewtest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Console {
    private final int n;
    private final Lock lock = new ReentrantLock();
    private final Condition conditionZero = lock.newCondition();
    private final Condition conditionOdd = lock.newCondition();
    private final Condition conditionEven = lock.newCondition();
    private int flag = 0;
    private int circle = 0;//交替唤醒

    public Console(int n) {
        this.n = n;
    }

    public void printZero() {

        for (int i = 0; i < n ; i++) {
            lock.lock();
            while (flag != 0) {
                try {
                    conditionZero.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.print(0);

            //first
            if (circle == 0) {
                flag = 1;
                conditionOdd.signal();

            } else {
                flag = 2;
                conditionEven.signal();
            }


            lock.unlock();
        }


    }

    public void printOdd() {

        for (int i = 1; i <= n; i += 2) {
            lock.lock();
            while (flag != 1) {
                try {
                    conditionOdd.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.print(i);
            flag = 0;
            circle = 1;
            conditionZero.signal();

            lock.unlock();
        }
    }


    public void printEven() {

        for (int i = 2; i <= n; i += 2) {
            lock.lock();
            while (flag != 2) {
                try {
                    conditionEven.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
            System.out.print(i);
            flag = 0;
            circle = 0;
            conditionZero.signal();

            lock.unlock();
        }

    }


}
